<template>
  <div class="org-container">
    <!-- <Search :tree-data="treeData"></Search> -->

    <!-- 当前层级列表 -->
    <transition name="fade">
      <div v-if="!currentChildren">
        <div v-for="item in localOrgList" :key="item.id" class="row">
          <!-- 部门行 -->
          <div
            v-if="item.children"
            class="row-department"
            @click.stop="showChildren(item)"
          >
            <div class="selection-container">
              <div
                class="selection-checkbox department-checkbox"
                :class="{
                  checked: item.checkedStatus === 'checked',
                  indeterminate: item.checkedStatus === 'indeterminate',
                }"
                @click.stop="handleToggleNodeSelection(item)"
              >
                <span v-if="item.checkedStatus === 'checked'" class="icon"
                  >✓</span
                >
                <span
                  v-else-if="item.checkedStatus === 'indeterminate'"
                  class="icon"
                  >-</span
                >
              </div>
            </div>
            <div class="content">
              <van-icon name="wap-home" />
              <span class="name">{{ item.label }}</span>
            </div>
            <div>
              <van-icon name="arrow" class="arrow-icon" />
            </div>
          </div>

          <!-- 成员行 -->
          <div v-else class="row-member">
            <div class="selection-container">
              <div
                class="selection-checkbox member-checkbox"
                :class="{ checked: item.checkedStatus === 'checked' }"
                @click.stop="handleToggleNodeSelection(item)"
              >
                <span v-if="item.checkedStatus === 'checked'" class="icon"
                  >✓</span
                >
              </div>
            </div>
            <div class="content">
              <van-icon name="user" />
              <span class="name">{{ item.label }}</span>
            </div>
          </div>
        </div>

        <div>
          选中项 {{ checkedNodes.length }}
          <div>
            <span v-for="item in checkedNodes" :key="item.id"
              >{{ item.label }}、</span
            >
          </div>
        </div>
      </div>
    </transition>

    <!-- 子层级列表 -->
    <transition name="slide-left">
      <div v-if="currentChildren" class="child-view">
        <div class="nav-bar">
          <div>
            <van-icon name="arrow-left" class="back-icon" @click="handleBack" />
            <span>返回上级</span>
          </div>
          <div class="all-selection" @click.stop="handleAllNodeSelection()">
            {{ isAllChecked ? "取消全选" : "全选" }}
          </div>
        </div>
        <Org :treeData="currentChildren" @change="handleChildrenChange" />
      </div>
    </transition>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Search from "@/components/Search";
export default {
  name: "Org",
  components: {
    Search,
  },
  props: {
    treeData: {
      type: Array,
      default: () => [],
      required: true,
    },
  },
  data() {
    return {
      currentChildren: null,
      localOrgList: [],
    };
  },
  computed: {
    ...mapState({
      checkedNodes: (state) => state.orgTree.checkedNodes,
    }),
    isAllChecked() {
      return this.currentChildren.every((item) => {
        return item.checkedStatus === "checked";
      });
    },
  },
  watch: {
    treeData: {
      deep: true,
      handler() {
        this.initLocalData();
      },
    },
  },
  created() {
    this.initLocalData();
  },
  methods: {
    initLocalData() {
      this.localOrgList = JSON.parse(JSON.stringify(this.treeData));
    },

    showChildren(item) {
      this.currentChildren = item.children;
    },

    // 切换节点
    handleUpdateCheckedNodes(node) {
      if (node.children && node.children.length > 0) return;
      if (node.checkedStatus === "checked") {
        this.$store.dispatch("orgTree/addNode", node);
      } else {
        this.$store.dispatch("orgTree/removeNode", node);
      }
    },

    toggleAllNodeSelection(item, status = "") {
      if (status) {
        item.checkedStatus = status;
      } else {
        item.checkedStatus =
          item.checkedStatus === "checked" ? "unchecked" : "checked";
      }
      console.log("修改状态", item.label, item.checkedStatus);
      this.handleUpdateCheckedNodes(item);

      if (item.children && item.children.length > 0) {
        item.children = item.children.map((child) => {
          this.toggleAllNodeSelection(child, item.checkedStatus);
          return child;
        });
      }
      return item;
    },

    handleToggleNodeSelection(item) {
      if (
        item.checkedStatus === "unchecked" ||
        item.checkedStatus === "indeterminate"
      ) {
        this.toggleAllNodeSelection(item, "checked");
      } else {
        this.toggleAllNodeSelection(item);
      }
      const index = this.localOrgList.findIndex((cur) => cur.id === item.id);
      this.localOrgList[index] = item;
      this.$emit("change", this.localOrgList);
    },

    handleAllNodeSelection() {
      const newChildData = this.currentChildren.map((item) => {
        this.handleToggleNodeSelection(item);
        return item;
      });
      this.handleChildrenChange(newChildData);
    },

    handleChildrenChange(newChildData) {
      // console.log("子组件数据更新===", newChildData);
      // console.log("当前孩子数据===", this.currentChildren);
      // console.log("当前层级数据===", this.localOrgList);

      this.currentChildren = newChildData;
      if (newChildData && newChildData.length > 0) {
        let checkCount = 0;
        let uncheckCount = 0;
        newChildData.forEach((item) => {
          if (item.checkedStatus === "checked") {
            checkCount++;
          } else if (item.checkedStatus === "unchecked") {
            uncheckCount++;
          }
        });

        // 判断父节点状态：["unchecked", "checked", "indeterminate"]
        let parentStatus = "unchecked";
        if (checkCount === newChildData.length) {
          parentStatus = "checked";
        } else if (uncheckCount === newChildData.length) {
          parentStatus = "unchecked";
        } else {
          parentStatus = "indeterminate";
        }

        const parentId = newChildData[0].parentId;
        const index = this.localOrgList.findIndex((cur) => cur.id === parentId);
        this.localOrgList[index].children = newChildData;
        this.localOrgList[index].checkedStatus = parentStatus;

        this.$emit("change", this.localOrgList);
      }
    },

    handleBack() {
      this.currentChildren = null;
    },
  },
};
</script>

<style scoped lang="less">
.org-container {
  width: 100%;
  height: 100%;
  padding: 10px;
}

.row {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  background: #fff;
  border-radius: 8px;
  padding: 0 15px;

  &-department,
  &-member {
    width: 100%;
    display: flex;
    align-items: center;
  }

  .selection-container {
    margin-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .content {
    flex: 1;
    display: flex;
    align-items: center;
  }

  .name {
    margin-left: 10px;
  }

  .arrow-icon {
    padding: 8px;
  }
}

.selection-checkbox {
  width: 18px;
  height: 18px;
  border: 1px solid #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;

  .icon {
    font-size: 12px;
    color: white;
  }

  &.checked {
    background-color: #1989fa;
    border-color: #1989fa;
  }

  &.indeterminate {
    background-color: #1989fa;
    border-color: #1989fa;
  }

  &.department-checkbox {
    border-radius: 4px;

    &.indeterminate .icon {
      font-weight: bold;
    }
  }
}

.child-view {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  z-index: 2;

  .nav-bar {
    height: 46px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
    background: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .back-icon {
      margin-right: 10px;
    }

    .all-selection {
      display: flex;
    }
  }

  .org-container {
    width: 100%;
    height: calc(100% - 46px);
    // height: 100%;
    overflow-y: auto;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform 0.3s ease;
}
.slide-left-enter-from {
  transform: translateX(100%);
}
.slide-left-leave-to {
  transform: translateX(100%);
}
</style>
